package problem113;

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

//113.路径总和2
//https://leetcode.cn/problems/path-sum-ii/?envType=problem-list-v2&envId=backtracking

class Solution {
    List<List<Integer>> ret = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    int sum = 0;
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        dfs(root, targetSum);
        return ret;
    }
    private void dfs(TreeNode root, int targetSum) {
        if(root == null) return;
        sum += root.val;
        list.add(root.val);
        if(sum == targetSum && root.left == null && root.right == null) {
            ret.add(new ArrayList(list));
        }
        dfs(root.left, targetSum);
        dfs(root.right, targetSum);
        sum -= root.val;
        list.remove(list.size()-1);
    }
}